package server.filter;

import server.model.factory.ModelFactory;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.JWTUtils;
import server.util.MyUtils;
import server.util.ResponseUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "tokenFilter", urlPatterns = "/*")
public class TokenFilter implements Filter {
    private final static String[] urls = {"/login", "/register", "/getGoodList", "/getGoodInfo",
            "/getGoodByKey", "/getEvaluationByGoodId", "/getStarAverage", "/getStatistic",
            "/getCommentByGoodId", "/getAuctionInfo", "/getOtherStoreInfo", "/getOtherUserInfo",
            "/getUserIdByStoreId"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        //默认info为认证失败
        Info info = InfoUtil.getInfo(InfoEnum.AUTH_ERROR);

        //获取url
        String path = ((HttpServletRequest) request).getRequestURI();
        System.out.println(path);

        boolean flag = false;
        for (int i = 0; i < urls.length; i++) {
            if (path.startsWith("/shop" + urls[i])) {
                flag = true;
                break;
            }
        }

        if (flag) {
            chain.doFilter(request, response); // 排除的url
            return;
        } else {
            //获取token
            String token = ((HttpServletRequest) request).getHeader("Token");
            //token不存在
            if (MyUtils.NOTNULL(token)) {
                Integer userId = ModelFactory.getTokenModel().judgeToken(token);
                System.out.println("user_id: " + userId);
                if (userId != null) {
                    if (JWTUtils.verify(token)) {
                        //设置userId到request，方便以后获取
                        request.setAttribute("userId", userId);
                        chain.doFilter(request, response);
                        return;
                    } else {
                        info = ModelFactory.getTokenModel().refreshToken(userId, token);
                    }
                }
            }
            ResponseUtil.responseMessage(((HttpServletResponse) response), info);
        }
    }

    @Override
    public void destroy() {

    }
}
